<template>
	<view class="container">
		<!-- 车辆信息卡片 -->
		<uni-card :is-shadow="true">
			<view slot="title" class="card-header">
				<view class="card-title">
					<uni-icons type="car" size="20" color="#fff"></uni-icons>
					<text>工作餐预约</text>
				</view>
			</view>

			<view class="card-body">
				<uni-forms ref="valiForm" :rules="rules" v-model="valiFormData" label-position="top" label-width="auto">
					<!-- 申请人信息 -->
					<uni-forms-item label="申请人" required name="username" class="custom-form-item">
						<view class="input-group">
							<uni-easyinput prefix-icon="person" v-model="valiFormData.username" placeholder="请输入姓名"
								:disabled="true" />
							<view class="icon-button" @click="showUserPicker" v-if="isAdmin">
								<uni-icons type="search" size="24" color="#1a73e8"></uni-icons>
							</view>
						</view>
					</uni-forms-item>

					<!-- 用户选择弹窗 -->
					<uni-popup ref="userPopup" type="bottom" background-color="#fff">
						<view class="popup-content">
							<view class="popup-header">
								<text class="popup-title">选择申请人</text>
								<uni-icons type="closeempty" size="24" color="#666"
									@click="closeUserPicker"></uni-icons>
							</view>
							<scroll-view scroll-y="true" class="user-list">
								<view v-if="userListLoading" class="loading">
									<uni-load-more status="loading"></uni-load-more>
								</view>
								<view v-else-if="userList.length === 0" class="empty">
									<text>暂无用户数据</text>
								</view>
								<view v-else>
									<view v-for="user in userList" :key="user._id" class="user-item"
										@click="selectUser(user)">
										<image :src="user.avatar || '/static/avatar/empty.png'" class="user-avatar"></image>
										<view class="user-info">
											<text class="username">{{ user.username }}</text>
											<text class="mobile">{{ user.mobile }}</text>
										</view>
									</view>
								</view>
							</scroll-view>
						</view>
					</uni-popup>

					<uni-forms-item label="电话" required name="mobile" class="custom-form-item">
						<uni-easyinput prefix-icon="phone" v-model="valiFormData.mobile" placeholder="请输入联系电话"
							:disabled="true" />
					</uni-forms-item>

					<!-- 类别 -->
					<uni-forms-item label="用餐形式" required name="type">
						<uni-data-select v-model="value" :localdata="list" @change="change"></uni-data-select>
					</uni-forms-item>

					<!-- 人数 -->
					<uni-forms-item label="人数" required name="num">
						<uni-easyinput prefix-icon="person" v-model="valiFormData.num" placeholder="请输入用餐人数" />
					</uni-forms-item>

					<!-- 随餐人员 -->
					<uni-forms-item v-if="Number(valiFormData.num) > 1" label="同餐人员" name="follower">
						<uni-easyinput prefix-icon="personadd" v-model="valiFormData.follower" placeholder="请输入共同用餐人员" />
					</uni-forms-item>

					<!-- 用餐时间 -->
					<uni-forms-item label="用餐时间" required name="dinner_time">
						<uni-datetime-picker type="datetime" v-model="valiFormData.dinner_time" @change="changeLog" />
					</uni-forms-item>

					<!-- 用餐地点 -->
					<uni-forms-item :required="value == 1" label="用餐地点" name="location">
						<uni-easyinput prefix-icon="location" :disabled="value == 2" v-model="valiFormData.location"
							placeholder="请输入送餐地点" />
					</uni-forms-item>

					<!-- 事由 -->
					<uni-forms-item label="事由" required name="reason" class="custom-form-item">
						<uni-easyinput prefix-icon="list" type="textarea" v-model="valiFormData.reason"
							placeholder="请填写用餐事由" />
					</uni-forms-item>

					<!-- 备注 -->
					<!-- <uni-forms-item  label="备注" name="note">
						<uni-easyinput prefix-icon="compose" v-model="valiFormData.note" placeholder="请输入备注" />
					</uni-forms-item> -->

					<button class="submit-btn" type="primary" @click="submit('valiForm')">
						<uni-icons type="paperplane" size="18" color="#fff"></uni-icons>
						<text>提交申请</text>
					</button>
				</uni-forms>
			</view>
		</uni-card>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				// 新增权限标识
				isAdmin: false,
				userinfo: {},
				userList: [],
				userListLoading: false,
				value: 1,
				list: [{
						value: 1,
						text: "盒饭"
					},
					{
						value: 2,
						text: "桌餐"
					},
				],
				valiFormData: {
					order_id: "",
					username: "",
					mobile: null,
					avatar:'',
					type: 0,
					num: 1,
					follower: null,
					dinner_time: null,
					location: "",
					reason: "",
					note: "",
					create_date: null,
					status: 0
				},
				rules: {
					username: {
						rules: [{
							required: true,
							errorMessage: '请输入申请人'
						}]
					},
					type: {
						rules: [{
							required: true,
							errorMessage: '请选择类别'
						}]
					},
					dinner_time: {
						rules: [{
							required: true,
							errorMessage: '请选择用餐时间'
						}]
					},
					num: {
						rules: [{
							required: true,
							errorMessage: '份数不能为空'
						}, {
							format: 'number',
							errorMessage: '份数只能输入数字'
						}, {
							pattern: '^[1-9][0-9]*$',
							errorMessage: '请输入一个正整数'
						}]
					},
					// location: {
					// 	rules: [{
					// 		required: true,
					// 		errorMessage: '请填写用餐地点',
					// 		trigger: 'blur'
					// 	}]
					// },
					reason: {
						rules: [{
							required: true,
							errorMessage: '请填写事由'
						}, {
							minLength: 4,
							errorMessage: '请填写4个字以上的事由'
						}]
					},
				},
			}
		},

		mounted() {
			const userInfo = uni.getStorageSync('userInfo')
			if (userInfo) {
				this.userinfo = userInfo
				// 新增权限检查
				this.isAdmin = this.userinfo.role?.value >= 5
				this.valiFormData.username = userInfo.username
				this.valiFormData.mobile = Number(userInfo.mobile)
				this.valiFormData.avatar = userInfo.avatar
			} else {
				uni.showToast({
					title: '请先登录',
					icon: 'none'
				})
			}
		},

		methods: {
			async showUserPicker() {
				this.userListLoading = true;
				this.$refs.userPopup.open();

				try {
					const userObj = uniCloud.importObject('users');
					const res = await userObj.getUserInfosimple();

					if (res.code === 0) {
						this.userList = res.data;
					} else {
						uni.showToast({
							title: '获取用户列表失败: ' + res.message,
							icon: 'none'
						});
					}
				} catch (e) {
					console.error('获取用户列表出错:', e);
					uni.showToast({
						title: '获取用户列表出错',
						icon: 'none'
					});
				} finally {
					this.userListLoading = false;
				}
			},

			closeUserPicker() {
				this.$refs.userPopup.close();
			},

			selectUser(user) {
				this.valiFormData.username = user.username;
				this.valiFormData.mobile = user.mobile;
				this.valiFormData.avatar = user.avatar;
				this.closeUserPicker();
			},
			change(e) {
				this.value = e.value
				this.valiFormData.type = e.value

			},
			changeLog(e) {
				this.valiFormData.dinner_time = e
			},
			submit(ref) {
				this.$refs[ref].validate().then(r => {
					// 格式化时间

					this.valiFormData.create_date = uni.$dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss')

					// 设置类型值
					this.valiFormData.type = this.value

					// 转换人数为数字
					this.valiFormData.num = Number(this.valiFormData.num)

					// 验证随餐人员
					if (this.valiFormData.num > 1 && !this.valiFormData.follower) {
						uni.showToast({
							title: '请输入随餐人员',
							icon: 'error'
						})
						return
					}

					// 生成订单号，格式：YYYYMMDDHHmmss + 6位随机数 + 用户ID后4位
					const now = uni.$dayjs(new Date()).format('YYYYMMDD');
					const randomNum = Math.floor(Math.random() * 900000) + 100000; // 6位随机数
					const userSuffix = this.userinfo._id.slice(-4); // 取用户ID后4位
					const order_id = `${now}-${randomNum}-${userSuffix}`;
					this.valiFormData.order_id = order_id

					// 调用云函数
					const obj = uniCloud.importObject('schedules')
					obj.addMealSchedules(this.valiFormData)
						.then(r => {
							if (r.code == 0) {
								this.sendsms()
								uni.showToast({
									title: r.message,
									icon: 'success'
								})
								setTimeout(() => {
									uni.$router.reLaunch({
										url: '/pages/user/service/menu',
										params: {
											activeIndex: 1
										}
									})
								}, 500)
							} else {
								uni.showToast({
									title: r.message,
									icon: 'none'
								})
							}
						})
						.catch(err => {
							//console.error('提交失败:', err)
							uni.showToast({
								title: '提交失败，请重试',
								icon: 'none'
							})
						})
				}).catch(err => {
					// //console.log('表单验证失败:', err)
				})
			},
			sendsms() {
				const obj = uniCloud.importObject('sms')
				const res = obj.approvesms().then(r => {
					if (r.statusCode == 200) {
						//console.log('发送成功')
					}
				})
			}
		}
	}
</script>

<style lang="scss">
	/* 通用样式 */
	.container {
		padding: 20rpx;
		background: linear-gradient(to bottom, #e6f0ff, #f0f7ff);
		min-height: 100vh;
	}

	.card-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		background: linear-gradient(90deg, #1a73e8, #4285f4);
		color: #fff;
		padding: 20rpx;
		border-radius: 16rpx 16rpx 0 0;

		.card-title {
			display: flex;
			align-items: center;

			text {
				margin-left: 10rpx;
				font-size: 32rpx;
			}
		}

		.available-cars {
			display: flex;
			align-items: center;
			background: rgba(255, 255, 255, 0.2);
			padding: 8rpx 20rpx;
			border-radius: 50rpx;
			font-size: 28rpx;

			text {
				margin-left: 8rpx;
			}
		}
	}

	.card-body {
		padding: 30rpx;

		.input-with-icon {
			position: relative;
			display: flex;
			align-items: center;

			.search-icon {
				position: absolute;
				right: 20rpx;
				z-index: 10;
			}
		}

		.popup-content {
			background-color: #fff;
			border-radius: 30rpx 30rpx 0 0;
			padding: 30rpx;
			max-height: 70vh;
		}

		.popup-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding-bottom: 20rpx;
			border-bottom: 1px solid #eee;
			margin-bottom: 20rpx;

			.popup-title {
				font-size: 32rpx;
				font-weight: bold;
				color: #333;
			}
		}

		.user-list {
			max-height: 60vh;

			.loading,
			.empty {
				display: flex;
				justify-content: center;
				align-items: center;
				padding: 40rpx 0;
				color: #999;
			}
		}

		.user-item {
			display: flex;
			align-items: center;
			padding: 20rpx 0;
			border-bottom: 1px solid #f5f5f5;

			&:last-child {
				border-bottom: none;
			}

			.user-avatar {
				width: 80rpx;
				height: 80rpx;
				border-radius: 50%;
				margin-right: 20rpx;
				background-color: #f0f7ff;
			}

			.user-info {
				display: flex;
				flex-direction: column;

				.username {
					font-size: 30rpx;
					color: #333;
					margin-bottom: 8rpx;
				}

				.mobile {
					font-size: 26rpx;
					color: #666;
				}
			}
		}

		.uni-forms {
			display: flex;
			flex-direction: column;
		}

		.custom-form-item {
			margin-bottom: 36rpx;
			padding: 10rpx 0;
			border-radius: 16rpx;
			background: #f8fafd;
			box-shadow: 0 4rpx 12rpx rgba(26, 115, 232, 0.08);

			.uni-forms-item__label {
				font-weight: bold;
				color: #1a73e8;
				font-size: 30rpx;
				padding: 16rpx 0 8rpx 20rpx;
				width: 100% !important;
				box-sizing: border-box;
				white-space: nowrap;
				text-align: left !important;
				display: block !important;
			}

			.uni-forms-item__content {
				padding: 0 20rpx 20rpx;
				width: 100%;
				box-sizing: border-box;
				display: block !important;
			}

			.uni-easyinput {
				width: 100%;
				display: block !important;
			}

			.uni-easyinput__content {
				border-radius: 12rpx !important;
				border: 1rpx solid #e0eaff !important;
				background: #fff;
				min-height: 80rpx;
				padding: 0 20rpx;
				transition: all 0.3s;
				width: 100%;
				box-sizing: border-box;
				display: block !important;

				&:hover,
				&:focus {
					border-color: #1a73e8 !important;
					box-shadow: 0 0 8rpx rgba(26, 115, 232, 0.2);
				}

				input,
				textarea {
					font-size: 28rpx;
					color: #333;
					width: 100%;
					display: block !important;
				}
			}

			.uni-datetime-picker {
				display: block !important;
				width: 100% !important;

				.uni-datetime-picker-select {
					width: 100% !important;
				}
			}
		}

		.people-input {
			.uniui-people {
				color: #1a73e8;
				font-size: 36rpx;
			}
		}

		/* #ifdef MP-WEIXIN */
		.uni-forms-item__label {
			padding-left: 0 !important;
			padding-right: 0 !important;
			color: #1a73e8 !important;
		}

		.uni-forms-item__content {
			padding-left: 0 !important;
			padding-right: 0 !important;
		}

		.uni-easyinput {
			padding: 0 !important;
		}

		/* #endif */

		.submit-btn {
			margin-top: 40rpx;
			background: linear-gradient(90deg, #1a73e8, #4285f4);
			height: 90rpx;
			line-height: 90rpx;
			border-radius: 16rpx;
			font-size: 32rpx;
			box-shadow: 0 8rpx 20rpx rgba(26, 115, 232, 0.3);
			display: flex;
			justify-content: center;
			align-items: center;
			font-weight: 500;
			letter-spacing: 2rpx;

			text {
				margin-left: 10rpx;
			}
		}

		.uni-forms-item__error {
			padding: 10rpx 20rpx;
			font-size: 24rpx;
			color: #ff5252;
			background: #fff0f0;
			border-radius: 8rpx;
			margin-top: 8rpx;
			display: block !important;
		}
	}

	.submit-btn {
		margin-top: 40rpx;
		background: linear-gradient(90deg, #1a73e8, #4285f4);
		height: 90rpx;
		line-height: 90rpx;
		border-radius: 16rpx;
		font-size: 32rpx;
		box-shadow: 0 8rpx 20rpx rgba(26, 115, 232, 0.3);
		display: flex;
		justify-content: center;
		align-items: center;
		font-weight: 500;
		letter-spacing: 2rpx;

		text {
			margin-left: 10rpx;
		}
	}

	/* 错误信息样式优化 */
	.uni-forms-item__error {
		padding: 10rpx 20rpx;
		font-size: 24rpx;
		color: #ff5252;
		background: #fff0f0;
		border-radius: 8rpx;
		margin-top: 8rpx;
		display: block !important;
	}

	.input-group {
		display: flex;
		align-items: center;
		// position: relative;
		// background-color: #fff;
		// border-radius: 12rpx;
		// border: 1rpx solid #e0eaff;
		// padding: 0 20rpx;
		// min-height: 80rpx;
		// box-sizing: border-box;

		.uni-easyinput {
			flex: 1;
		}

		.icon-button {
			display: flex;
			align-items: center;
			justify-content: center;
			width: 60rpx;
			height: 60rpx;
			margin-left: 10rpx;
		}
	}

	/* 可选：去除 easyinput 内部右侧 padding，避免文字被挤压 */
	.uni-easyinput__content {
		padding-right: 0 !important;
	}
</style>